package com.qf.spring.mybatis.controller;

import com.qf.spring.mybatis.entity.User;
import com.qf.spring.mybatis.service.UserService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@WebServlet("/Login")
public class LoginServlet extends HttpServlet {

    private UserService userService;

    @Override
    public void init() throws ServletException {
        // 在初始化方法中给userService赋值，通过web容器，获取Spring的上下文
        WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
        userService = context.getBean("userService", UserService.class);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 获取参数
        String name = request.getParameter("name");
        String password = request.getParameter("password");
        // 调用service.login
        User user = userService.login(name, password);
        if(Objects.nonNull(user)){
            // 成功，转发到成功页面
            request.getRequestDispatcher("/success.jsp").forward(request,response);
        }else {
            // 登录失败，重定向到登录页面
            request.setAttribute("error","用户名或密码错误！");
            request.getRequestDispatcher("/index.jsp").forward(request,response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
